// store/permission.js
import _ from 'lodash'
import { asyncRouterMap, constantRouterMap } from '@/router'
import { rolesMap } from '@/settings'

const { admins } = rolesMap || {}

// 是否有权限
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    const intersectionRoles = _.intersection(roles, route.meta.roles)
    return !!intersectionRoles.length
  } else {
    return true
  }
}

// 是否管理员
function isAdmin(roles) {
  const intersectionRoles = _.intersection(roles, admins)
  return !!intersectionRoles.length
}

// 获取路由
const getRouter = (routerMap, roles) => {
  const routers = []
  for (const item of routerMap) {
    const routerItem = Object.assign({}, item, {
      hidden: !hasPermission(roles, item) || item.hidden
    })
    if (item.children && item.children.length) {
      const children = getRouter(item.children, roles)
      Object.assign(routerItem, {
        children
      })
    }
    routers.push(routerItem)
  }
  return routers
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      const { roles } = data
      return new Promise(resolve => {
        let accessedRouters = []

        if (isAdmin(roles)) {
          accessedRouters = asyncRouterMap
        } else {
          accessedRouters = getRouter(asyncRouterMap, roles)
        }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
